import { createRouter, createWebHistory, type RouteRecordRaw } from "vue-router"
import { flatMultiLevelRoutes } from "./helper"
import routeSettings from "@/config/route"
import { useUserStore } from "@/store/modules/user"
import { ElMessage } from "element-plus"

const Layouts = () => import("@/layouts/index.vue")

/**
 * 常驻路由
 * 除了 redirect/403/404/login 等隐藏页面，其他页面建议设置 Name 属性
 */
export const constantRoutes: RouteRecordRaw[] = [
  {
    path: "/login",
    component: () => import("@/views/login/index.vue"),
    meta: {
      hidden: true
    }
  },
  {
    path: "/",
    component: Layouts,
    redirect: "/account",
    name: "Table",
    meta: {
      title: "活动",
      elIcon: "Promotion"
    },
    children: [
      {
        path: "account",
        component: () => import("@/views/table/account/index.vue"),
        name: "Account",
        meta: {
          title: "账号管理",
          keepAlive: true,
          elIcon: "user"
        }
      },
      {
        path: "works",
        component: () => import("@/views/table/works/index.vue"),
        name: "Works",
        meta: {
          title: "作品管理",
          keepAlive: true,
          elIcon: "files"
        }
      },
      {
        path: "evaluate",
        component: () => import("@/views/table/evaluate/index.vue"),
        name: "Evaluate",
        meta: {
          title: "评价管理",
          keepAlive: true,
          elIcon: "edit"
        }
      }
    ]
  }
]

/**
 * 动态路由
 * 用来放置有权限 (Roles 属性) 的路由
 * 必须带有 Name 属性
 */
export const asyncRoutes: RouteRecordRaw[] = []

const router = createRouter({
  history: createWebHistory(),
  routes: routeSettings.thirdLevelRouteCache ? flatMultiLevelRoutes(constantRoutes) : constantRoutes
})

const authUrl = ["/account", "/works", "/evaluate"]
/** 重置路由 */
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  if (!authUrl.includes(to.path)) {
    next()
  }
  if (userStore.token === "" && authUrl.includes(to.path)) {
    next("/login")
    ElMessage.warning("登录超时,请重新登录")
  } else {
    next()
  }
})

export default router
